# """
#        @File     : pre3.py
#        @IDE      : PyCharm
#        @Author   : 陈引弟
#        @Date     : 2025/3/12 19:52
#        @Desc     :
# =========================================================
# """
# import pandas as pd
# from datetime import timedelta
# from sklearn.model_selection import train_test_split
# from sklearn.ensemble import RandomForestRegressor
# from sklearn.linear_model import LinearRegression
# import numpy as np
#
# # --------------------- 数据预处理 ---------------------
# # 加载数据
# df = pd.read_csv(r'F:\python\基于大数据的天气预测分析系统2\model\weather.csv')
# df['Date'] = pd.to_datetime(df['Date'])
#
#
# # 提取日期特征
# def extract_date_features(df):
#     df['year'] = df['Date'].dt.year
#     df['month'] = df['Date'].dt.month
#     df['dow'] = df['Date'].dt.dayofweek     # 星期几（0=周一, 6=周日）
#     df['dom'] = df['Date'].dt.day           # 每月第几天
#     df['weekend'] = (df['dow'] >= 5).astype(int)  # 周末标记
#
#     return df
#
# df = extract_date_features(df)
#
# # 定义特征和目标列
# features = ['year', 'month', 'dow', 'dom', 'weekend']
# X = df[features]
# y = df['Temp']
#
# # 划分训练集和测试集
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
#
# # --------------------- 模型训练 ---------------------
# # 随机森林回归
# rf_model = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)
# rf_model.fit(X_train, y_train)
#
# # 线性回归
# lr_model = LinearRegression()
# lr_model.fit(X_train, y_train)
#
# # --------------------- 未来7天预测 ---------------------
# # 生成未来7天日期
# last_date = df['Date'].max()
# future_dates = pd.date_range(start=last_date + timedelta(days=1), periods=7)
#
# # 构造未来数据集
# future_df = pd.DataFrame({'Date': future_dates})
# future_df = extract_date_features(future_df)
# X_future = future_df[features]
#
# # 预测气温
# future_df['RF_Predicted_Temp'] = rf_model.predict(X_future)
# future_df['LR_Predicted_Temp'] = lr_model.predict(X_future)
#
# # --------------------- 结果输出 ---------------------
# print("未来7天气温预测结果（随机森林 vs 线性回归）:")
# print(future_df[['Date', 'RF_Predicted_Temp', 'LR_Predicted_Temp']])
#
# # --------------------- 模型评估 ---------------------
# # 计算测试集上的均方误差（MSE）
# from sklearn.metrics import mean_squared_error
#
# rf_test_pred = rf_model.predict(X_test)
# lr_test_pred = lr_model.predict(X_test)
#
# print("\n模型评估（测试集）:")
# print(f"随机森林 MSE: {mean_squared_error(y_test, rf_test_pred):.2f}")
# print(f"线性回归 MSE: {mean_squared_error(y_test, lr_test_pred):.2f}")


"""
       @File     : pre3.py
       @IDE      : PyCharm
       @Author   : 陈引弟
       @Date     : 2025/3/12 19:52
       @Desc     : 基于历史气温的时间序列预测
=========================================================
"""
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# --------------------- 数据预处理 ---------------------
# 加载数据并排序
df = pd.read_csv(r'F:\python\基于大数据的天气预测分析系统\model\weather.csv')
df['Date'] = pd.to_datetime(df['Date'])
df = df.sort_values('Date').reset_index(drop=True)

# 创建滞后特征（使用过去10天的温度）
lags = 15  # 可调整滞后天数
for i in range(1, lags + 1):
    df[f'lag_{i}'] = df['Temp'].shift(i)

# 删除包含NaN的行
df = df.dropna()

# 定义特征和目标列
features = [f'lag_{i}' for i in range(1, lags + 1)]
X = df[features]
y = df['Temp']

# 划分训练集和测试集（保持时间顺序）
test_size = 7  # 用最后7天作为测试集
X_train, X_test = X[:-test_size], X[-test_size:]
y_train, y_test = y[:-test_size], y[-test_size:]

# --------------------- 模型训练 ---------------------
# 随机森林回归
rf_model = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)
rf_model.fit(X_train, y_train)

# 线性回归
lr_model = LinearRegression()
lr_model.fit(X_train, y_train)


# --------------------- 未来7天预测 ---------------------
def predict_future(model, last_known_data, steps=7, lags=15):
    predictions = []
    current_data = last_known_data.copy()

    for _ in range(steps):
        # 预测下一天
        pred = model.predict([current_data[-lags:]])[0]
        predictions.append(pred)

        # 更新数据窗口
        current_data = np.append(current_data[1:], pred)

    return predictions


# 获取最近可用的滞后数据
last_known = df[features].values[-1]

# 进行预测
rf_predictions = predict_future(rf_model, last_known)
lr_predictions = predict_future(lr_model, last_known)

# 生成未来日期
last_date = df['Date'].max()
future_dates = pd.date_range(start=last_date + pd.Timedelta(days=1), periods=7)

# 创建结果DataFrame
future_df = pd.DataFrame({
    'Date': future_dates,
    'RF_Predicted_Temp': rf_predictions,
    'LR_Predicted_Temp': lr_predictions
})

# --------------------- 结果输出 ---------------------
print("\n未来7天气温预测结果（随机森林 vs 线性回归）:")
print(future_df[['Date', 'RF_Predicted_Temp', 'LR_Predicted_Temp']])

# --------------------- 模型评估 ---------------------
# 在测试集上评估
rf_test_pred = rf_model.predict(X_test)
lr_test_pred = lr_model.predict(X_test)

print("\n模型评估（测试集最后7天）:")
print(f"随机森林 MSE: {mean_squared_error(y_test, rf_test_pred):.2f}")
print(f"线性回归 MSE: {mean_squared_error(y_test, lr_test_pred):.2f}")